﻿using Enter.Admin.Models;
using Enter.Admin.Utils;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Enter.Admin.Filters
{
    // https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-5.0
    // [ExceptionFilter]
    // [TypeFilter(typeof(ExceptionFilter))]
    /*
     services.AddMvc(config =>
        {
            config.Filters.Add(new ResultFilter());
            config.Filters.Add(new ExceptionFilter());
            options.Filters.Add<HttpGlobalExceptionFilter>();
            config.Filters.Add(typeof(CacheResourceFilter));
    
        });
     */
    public class ExceptionFilter : IExceptionFilter
    {
        private readonly IWebHostEnvironment _hostingEnvironment;
        private readonly IModelMetadataProvider _modelMetadataProvider;
        private readonly ILogger<ExceptionFilter> _logger;
        public ExceptionFilter(ILogger<ExceptionFilter> logger, IWebHostEnvironment hostingEnvironment,IModelMetadataProvider modelMetadataProvider)
        {
            _logger = logger;
            _hostingEnvironment = hostingEnvironment;
            _modelMetadataProvider = modelMetadataProvider;
        }
        public void OnException(ExceptionContext context)
        {
            //if (!_hostingEnvironment.IsDevelopment())
            //{
            //    return;
            //}
            _logger.LogError(context.Exception, string.Format("OnException:{0}", context.Exception.Message));
            if (context.HttpContext.Request.IsAjax())
            {
                var error = new ResponseResult<string>(false, context.Exception == null ? "请求异常." : context.Exception.Message);
                context.Result = new JsonResult(error);
            }
            else 
            {
                var result = new ViewResult { ViewName = "Error" };
                result.ViewData = new ViewDataDictionary(_modelMetadataProvider, context.ModelState);
                result.ViewData.Add("Exception", context.Exception);
                context.Result = result;
            }
            //context.HttpContext.Response.WriteAsync($"{GetType().Name} in. \r\n");
        }
    }
}
